package com.mxx.common.payment.apple;

import com.mxx.common.payment.*;
import com.mxx.common.exception.MissingRequiredPropertiesException;
import com.mxx.common.exception.UnImplementedException;

import java.util.Map;

public class DefaultApplePaymentHandler implements PaymentHandler<ApplePrepaymentResponse> {
    private ApplePaymentParameter paymentParameter;

    public DefaultApplePaymentHandler(ApplePaymentParameter paymentParameter) {
        this.paymentParameter = paymentParameter;
    }

    @Override
    public ApplePrepaymentResponse prepaymentProcess(TradeMark tradeMark) {
        ApplePrepaymentResponse prepaymentResponse = new ApplePrepaymentResponse();
        prepaymentResponse.setProductId(String.format("%s%s", paymentParameter.getAppId(), tradeMark.getAmount()))
                .setTradeNo(tradeMark.getTradeId());
        return prepaymentResponse;
    }

    @Override
    public void paymentFallback(FinishTradeHandler paymentHandler, Map<String, String> params) {
        String tradeNo = params.get("tradeNo");
        if (tradeNo == null || tradeNo.isEmpty()) {
            throw new MissingRequiredPropertiesException(" [tradeNo] missing . The return value of Apple payment is missing the order number, and the order number needs to be supplemented manually !");
        }
        Object status = params.get("status");
        if (status.equals(0)) {
            Object data = params.get("receipt");
            if (data instanceof Map) {
                String operatorId = ((Map<String, String>) data).get("transaction_id");
                paymentHandler.paymentSuccessfully(TradeType.Apple, tradeNo, operatorId);
                return;
            }

        }
        paymentHandler.paymentFailure(TradeType.Apple, tradeNo, null, String.valueOf(status), "支付已关闭");

    }

    @Override
    public PayResponse close(String orderNo) {
        PayResponse payResponse = new PayResponse();
        payResponse.setOutTradeNo(orderNo);
        payResponse.setTradeState("SUCCESS");
        payResponse.setTradeStateDesc("支付已关闭");
        return payResponse;
    }

    @Override
    public void refund(FinishTradeHandler finishTradeHandler, String outTradeNo, String totalAmount, String refundAmount, String refundReason) {

    }

    @Override
    public boolean analysisOfRefund(FinishTradeHandler paymentHandler, Map<String, String> params) {
        return false;
    }

    @Override
    public void selectPayment(FinishTradeHandler finishTradeHandler, String outTradeNo) {
        finishTradeHandler.paymentFailure(TradeType.Apple, outTradeNo, null, "NOT SELECT", "支付已关闭");
    }

    @Override
    public PayResponse selectOfRefund(String outTradeNo, String operatorId) {
        throw new UnImplementedException("current method not implemented ");
    }

    @Override
    public TradeType getTradeType() {
        return TradeType.Apple;
    }
}
